package com.bqjr.cloud.zuul.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class SpringConfig {
	
	@Autowired
    private Environment env;
	
	@Bean
    public DataSource dataSource() {
		String driverClassName = env.getProperty("spring.datasource.driver-class-name");
		String url = env.getProperty("spring.datasource.url");
		String username = env.getProperty("spring.datasource.username");
		String password = env.getProperty("spring.datasource.password");
		int initSize = Integer.parseInt(env.getProperty("spring.datasource.init-size"));
		int maxActive = Integer.parseInt(env.getProperty("spring.datasource.max-active"));
		int minIdle = Integer.parseInt(env.getProperty("spring.datasource.min-idle"));
		int maxIdle = Integer.parseInt(env.getProperty("spring.datasource.max-idle"));
		int maxWait = Integer.parseInt(env.getProperty("spring.datasource.max-wait"));
		int maxAge = Integer.parseInt(env.getProperty("spring.datasource.max-age"));
		
		org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
		dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setInitialSize(initSize);
        dataSource.setMaxActive(maxActive);
        dataSource.setMinIdle(minIdle);
        dataSource.setMaxIdle(maxIdle);
        dataSource.setMaxWait(maxWait);
        dataSource.setMaxAge(maxAge);
        dataSource.setTestOnBorrow(true);
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnReturn(false);
		dataSource.setRemoveAbandoned(true);
		dataSource.setValidationInterval(3000);
		dataSource.setNumTestsPerEvictionRun(maxActive);
		dataSource.setTimeBetweenEvictionRunsMillis(300000);
		dataSource.setMinEvictableIdleTimeMillis(600000);
		dataSource.setValidationQuery("SELECT 1");
        return dataSource;
    }
	
	@Bean
    public PlatformTransactionManager txManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
	
}
